package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
	"zg3/config"
	"zg3/internal/models/dao"
	"zg3/internal/models/service"
)

type GroupNode struct {
	conn    *websocket.Conn
	data    chan []byte
	groupId []int
}

var GroupClientChat = make(map[int]*GroupNode)

func GroupChat(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("userId"))
	upgrade := websocket.Upgrader{
		//允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, _ := upgrade.Upgrade(c.Writer, c.Request, nil)
	node := &GroupNode{
		conn:    conn,
		data:    make(chan []byte, 1024),
		groupId: []int{},
	}

	id := service.FindGroupId(userId)

	for _, member := range id {
		node.groupId = append(node.groupId, member.GroupId)
	}

	GroupClientChat[userId] = node

	go GroupSendMessage(node)

	go GroupReadMessage(node)

}

func GroupSendMessage(node *GroupNode) {
	for {
		select {
		case data := <-node.data:
			err := node.conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				node.conn.Close()
				return
			}
		}
	}
}

func GroupReadMessage(node *GroupNode) {
	for {
		_, i, err := node.conn.ReadMessage()
		if err != nil {
			node.conn.Close()
			return
		}
		var message *dao.GroupMessage
		json.Unmarshal(i, &message)
		config.DB.Create(&message)
		for _, groupNode := range GroupClientChat {
			for _, i2 := range groupNode.groupId {
				if i2 == message.GroupId {
					groupNode.data <- i
				}
			}
		}
	}
}
